#include <stdio.h>
#include <signal.h>

#include <ijpege.h>
#include <cliijpege.h>
#ifdef DMALLOC
#include <imp/dmalloc.h>
#endif
/* Ctrl-C handler */
static volatile int b_ctrl_c = 0;
static void sigint_handler(int a)
{
	b_ctrl_c = 1;
}

int main(int argc, char **argv)
{
	ijpege_param_t param;
	cli_opt_t opt;
    ijpege_ql_param_t ql_param;
	int ret = 0;

    memset(&ql_param, 0, sizeof(ql_param));

	/* init ijpege_param_t */
	if ((ret = init(argc, argv, &param, &opt)) < 0) {
		fprintf(stderr, "init failed\n");
		goto err_init;
	}

    if ((opt.i_ql > 0) && (opt.i_ql < 256)) {
        ql_param.user_ql_en = 1;
        MakeTables(opt.i_ql, &(ql_param.qmem_table[0]), &(ql_param.qmem_table[64]));
    }

	/* Control-C handler */
	signal(SIGINT, sigint_handler);

	if ((ret = encode(&param, &opt, &b_ctrl_c, ql_param.user_ql_en ? &ql_param : NULL)) < 0) {
		fprintf(stderr, "encode failed\n");
		goto err_encode;
	}

	/* deinit ijpege_param_t */
	deinit(&param, &opt);

	return ret;

err_encode:
	deinit(&param, &opt);
err_init:
	return -1;
}
